package com.maijinjie.website.content.action;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.maijinjie.common.action.dwz.DwzUIBaseAction;
import com.maijinjie.common.bean.Pagination;
import com.maijinjie.common.bean.StatusBean;
import com.maijinjie.admin.content.bean.ArticalNewsBean;
import com.maijinjie.admin.content.bean.OnlineEnrollmentBean;
import com.maijinjie.admin.content.bean.PictureNewsBean;
import com.maijinjie.admin.content.bean.TableDownloadInfoBean;
import com.maijinjie.admin.content.bean.VideoNewsBean;
import com.maijinjie.admin.content.service.ArticalNewsService;
import com.maijinjie.admin.content.service.CookListService;
import com.maijinjie.admin.content.service.OnlineEnrollmentService;
import com.maijinjie.admin.content.service.PictureNewsService;
import com.maijinjie.admin.content.service.TableDownloadInfoService;
import com.maijinjie.admin.content.service.VideoNewsService;
import com.maijinjie.admin.content.field.PictureNewsFields;
import com.maijinjie.common.session.SessionContext;
import com.maijinjie.common.upload.bean.FileVo;
import com.maijinjie.common.util.PoiExcelUtil;

/**
 * PictureNewsAction
 * @version 1.0
 * @author 罗正杰
 */
@Controller
@RequestMapping(value="/")
public class WebSiteAction {
	/** 用户服务接口 */
	@Resource
	PictureNewsService pictureNewsService;

	@Resource
	VideoNewsService videoNewsService;
	
	@Resource
	ArticalNewsService articalNewsService;
	
	@Resource
	TableDownloadInfoService tableDownloadInfoService;
	
	@Resource
	OnlineEnrollmentService onlineEnrollmentService;
	
	@Resource
	CookListService cookListService;
	
	/**
	 * 查询数据
	 * @param pageNum
	 * @param numPerPage
	 * @param pagination
	 * @param model
	 * @return String
	 * @throws Exception
	 */
	@RequestMapping(value="/picture/{type}")
	public String listPicture(@PathVariable("type")String type,Model model,HttpServletRequest request) throws Exception{
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("type", type);
		request.setAttribute("type", type);
		model.addAttribute("result",pictureNewsService.list(params));
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath(type);
	
	}
	
	@RequestMapping(value="/picturelist/{type}")
	public String listPictureList(@PathVariable("type")String type,Model model,HttpServletRequest request) throws Exception{
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("type", type);
		request.setAttribute("type", type);
		model.addAttribute("result",pictureNewsService.listWithPicList(params));
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath(type);
	}
	
	
	@RequestMapping(value="/video/{type}")
	public String listVideo(@PathVariable("type")String type,Model model,HttpServletRequest request) throws Exception{
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("type", type);
		request.setAttribute("type", type);
		model.addAttribute("result",videoNewsService.list(params));
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath(type);
	}
	
	@RequestMapping(value="/videopicture/{type}")
	public String listPictureVideo(@PathVariable("type")String type,Model model,HttpServletRequest request) throws Exception{
		Map<String,Object> params = new HashMap<String,Object>();
		Map<String,List> result = new HashMap<String,List>();
		params.put("type", type);
		result.put("video", videoNewsService.list(params));
		result.put("picture", pictureNewsService.list(params));
		request.setAttribute("type", type);
		model.addAttribute("result",result);
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath(type);
	}	
	
	
	
	@RequestMapping(value="/cookList/{type}")
	public String listCookList(@PathVariable("type")String type,Model model,HttpServletRequest request) throws Exception{
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("type", type);
		Map<String,List> result = this.cookListService.listAllByCateory(params);
		request.setAttribute("type", type);
		model.addAttribute("result",result);
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath(type);
	}
	
	
	
	@RequestMapping(value="/artical/{type}")
	public String listArtical(@PathVariable("type")String type,Model model,HttpServletRequest request) throws Exception{
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("type", type);
		request.setAttribute("type", type);
		model.addAttribute("result",articalNewsService.list(params));
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath(type);
	}
	
	@RequestMapping(value="/download/{type}")
	public String listDownload(@PathVariable("type")String type,Model model,HttpServletRequest request) throws Exception{
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("type", type);
		request.setAttribute("type", type);
		model.addAttribute("result",tableDownloadInfoService.listFileByCategory(params));
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath(type);
	}	
	
	@RequestMapping(value="/downloadfile/{id}")
	public void donwloadFile(@PathVariable("id")String id,HttpServletResponse response,HttpServletRequest request) throws Exception{

		TableDownloadInfoBean vo = this.tableDownloadInfoService.getBeanById(Integer.parseInt(id));
		if(vo !=null){
			if(vo.getEndfix().equals("pdf")){
				response.setHeader("Content-type", "application/pdf");
			}else if(vo.getEndfix().equals("doc")||vo.getEndfix().equals("docx")){
				response.setHeader("Content-type", "application/msword");
			}else if(vo.getEndfix().equals("xls")||vo.getEndfix().equals("xlsx")){
				response.setHeader("Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			}
			response.setHeader("Content-Disposition", "attachment; filename=" + new String(vo.getName().getBytes("utf-8"), "ISO8859-1"));
			URL url = new URL(vo.getPath());
			URLConnection conn = url.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			OutputStream os = response.getOutputStream();
			byte[] arr = new byte[1024];
			int size = 0;
			while((size =is.read(arr))!=-1){
				os.write(arr,0,size);
			}
			os.flush();
			os.close();
		}
	}
	
	
	@RequestMapping(value="/articalwithdate/{type}")
	public String listArticalWithDate(@PathVariable("type")String type,Model model,HttpServletRequest request) throws Exception{
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("type", type);
		request.setAttribute("type", type);
		model.addAttribute("result",articalNewsService.listWithDate(params));
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath(type);
	}
	
	
	
	@RequestMapping(value="/articalbyid/{type}")
	public String listArticalById(@PathVariable("type")String type,Model model,HttpServletRequest request,String id) throws Exception{
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("id", id);
		request.setAttribute("type", type);
		model.addAttribute("result",articalNewsService.list(params).get(0));
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath(type);
	}
	
	
	@RequestMapping(value="/staticPage/{type}")
	public String listStatic(@PathVariable("type")String type,Model model,HttpServletRequest request) throws Exception{
		request.setAttribute("type", type);
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath(type);
	}
	
	@RequestMapping(value="/index")
	public String index(Model model,HttpServletRequest request) throws Exception{
		request.setAttribute("type", "index");
		Map<String,Object> params = new HashMap<String,Object>();
		Map<String,Object> result = new HashMap<String,Object>();
		//温馨提示
		params.put("type", "rel0-0");		
		result.put("rel0-0", this.articalNewsService.list(params));
		
		//童言无忌
		params.put("type", "rel6-5");
		result.put("rel6-5", getElement(this.articalNewsService.list(params),1));
		
		//园舍环境
		params.clear();
		params.put("type", "rel1-3");
		result.put("rel1-3",getElement(this.pictureNewsService.list(params),5));
		
		//精彩视频
		params.clear();
		params.put("type", "rel3-4");
		List<VideoNewsBean> temp = this.videoNewsService.list(params);
		if(temp.size()>0){
			result.put("rel3-4",temp.get(0).getVideoPath());
		}else{
			result.put("rel3-4","");
		}
		//教养有方
		params.clear();
		params.put("type", "rel6-4");
		result.put("rel6-4",this.articalNewsService.listWithDate(params).get("result").get(0));
		
		//最新动态
		params.clear();
		params.put("type", "rel3-1");
		result.put("rel3-1",this.articalNewsService.listWithDate(params).get("result").get(0));
		
		//提示语
		params.put("type", "index");		
		result.put("index", this.articalNewsService.list(params));
		
		model.addAttribute("result",result);
		addFooterInfo(request);
		return WebSiteStaticContainer.getPagePath("index");
	}
	
	private Object getElement(List list, int i) {		
		if(list != null && list.size()>0 ){
				if(i == 1){
					if(list.size()>=1){
						return list.get(0);
					}else{
						return null;
					}
				}else{
					int j = list.size()<i?list.size() : i;
					List result = new ArrayList();
					for(int k =0 ; k< j ;k++){
						result.add(list.get(k));
					}
					return result;
				}
		}else{
			return list;
		}
	}

	@RequestMapping(value="/search")
	public String search(Model model,HttpServletRequest request,String searchStr,Integer pageNum) throws Exception{
		searchStr= new String(searchStr.getBytes("ISO8859-1"), "UTF-8");
		Map<String,Object> params = new HashMap<String,Object>();
		Pagination pagination = new Pagination();
		pagination.getParamMap().put("title", searchStr==null?"":searchStr);
		pagination.setPage(pageNum);
		List<ArticalNewsBean> result =  this.articalNewsService.list(pagination).getList();
		for(Iterator<ArticalNewsBean> it = result.iterator(); it.hasNext();){
			ArticalNewsBean bean = it.next();
			if(bean.getTitle() == null || "".equals(bean.getTitle())){
				it.remove();
			}else{
				bean.setTitle(bean.getTitle().replace(searchStr, "<em>"+searchStr+"</em>"));
			}
		}
		model.addAttribute("pagination",pagination);
		request.setAttribute("searchStr", searchStr);
		request.setAttribute("type", "search");
		return WebSiteStaticContainer.getPagePath("search");
	}
	
	@RequestMapping(value="/submitEnrollment")
	public String saveOnlineEnrollment(HttpServletRequest request) throws Exception{
		Map<String,Object> params = new HashMap<String,Object>();

		
		String name = request.getParameter("name");
		String type = request.getParameter("type");
		String email = request.getParameter("email");
		String topic = request.getParameter("topic");
		String content = request.getParameter("content");
		OnlineEnrollmentBean oe = new OnlineEnrollmentBean();
		oe.setName(name);
		oe.setEmail(email);
		oe.setTitle(topic);
		oe.setContent(content);
		oe.setType(type);
		oe.setCreateDate(new Date());
		String msg = "";
		try {
			StatusBean status = onlineEnrollmentService.save(oe, null, null);
			msg = status.getMessage();
		} catch (Exception e) {
			msg = "保存错误";
		} 
		
		//提示语
		params.put("type", type);		
		request.setAttribute("result", this.articalNewsService.list(params));
		request.setAttribute("msg", msg);
		String forwardurl = request.getParameter("forwardurl");
		if(forwardurl != null && !"".equals(forwardurl)){
			addFooterInfo(request);
			return "forward:"+forwardurl; 
		}else{
			request.setAttribute("type", type);
			
			addFooterInfo(request);
			return WebSiteStaticContainer.getPagePath(request.getParameter("type"));
		}
	}
	
	private void addFooterInfo(HttpServletRequest request) throws Exception {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("type", "footer");
		request.setAttribute("footer_link", this.articalNewsService.list(params));
		request.setAttribute("footer_fan", this.pictureNewsService.list(params));
	}
	
}

